package open.panxiong.shared.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import fi.iki.elonen.NanoHTTPD
import open.panxiong.shared.R
import open.panxiong.shared.activity.MainActivity
import open.panxiong.shared.http.NanohttpdHttp
import open.panxiong.shared.service.binder.NanohttpdBinder


class NanohttpdService : Service() {
    companion object {
        const val LOG_TAG = "NanohttpdService"
        const val NOTIFICATION_ID = 0x123456
        const val CHANNEL_ID = "AND_SHARE_NOTIFICATION_CHANNEL_ID"
        const val CHANNEL_NAME = "AND_SHARE_NOTIFICATION_CHANNEL_NAME"
        const val SERVER_PORT = 8090
    }

    private lateinit var notification: Notification
    private lateinit var nanohttpd: NanoHTTPD
    private lateinit var binder: NanohttpdBinder

    override fun onBind(intent: Intent): IBinder {
        binder = NanohttpdBinder(this)
        return binder
    }

    @SuppressLint("LaunchActivityFromNotification")
    override fun onCreate() {
        super.onCreate()
        Log.d(LOG_TAG, "服务创建")

        this.createNotificationChannel()

        notification = this.createNotificationBody()

        nanohttpd = NanohttpdHttp(SERVER_PORT, this)
    }

    // 每次点击时触发
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        this.startNanohttpd()

        return START_STICKY
    }

    // 被从任务管理器强制删除时触发
    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        Log.d(LOG_TAG, "强制退出")
        stopSelf()
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onDestroy() {
        super.onDestroy()
        Log.d(LOG_TAG, "服务销毁")
        this.stopNanohttpd()
    }

    @SuppressLint("ForegroundServiceType")
    fun startNanohttpd() {
        var isCompleted = false
        try {
            if (!nanohttpd.isAlive) {
                nanohttpd.start()

                startForeground(NOTIFICATION_ID, notification)

                Log.d(LOG_TAG, "服务开始 NanoHTTPD启动成功 ${nanohttpd.hostname}:$SERVER_PORT ")
            } else {
                Log.d(LOG_TAG, "服务开始 NanoHTTPD已在运行 ${nanohttpd.hostname}:$SERVER_PORT")
            }
            isCompleted = true
        } catch (e: Exception) {
            Log.e(LOG_TAG, "服务开始 NanoHTTPD启动失败", e)
            isCompleted = false
        } finally {
            MainActivity.nanohttpdServiceState.value = isCompleted
        }
    }

    @RequiresApi(Build.VERSION_CODES.N)
    @SuppressLint("WrongConstant")
    fun stopNanohttpd() {
        stopForeground(NOTIFICATION_ID)
        nanohttpd.stop()
    }

    // Android O 以上创建通知需要一个渠道
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val default = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, default)
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    private fun createNotificationBody(): Notification {
        val notificationIntent = Intent(this, MainActivity::class.java) // 点击通知时打开的页面
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT
            )
        }
        val name = getString(R.string.app_name)
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("$name 共享服务在运行")
            .setContentText("点击回到程序")
            .setSmallIcon(R.drawable.ic_launcher_logo)
            .setContentIntent(pendingIntent) // 可以设置点击通知后的操作
            .build()
    }

}